"""
生成 OpenAPI 文档
"""
import json
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from fastapi.openapi.utils import get_openapi
from ASR.main import app

# 生成 OpenAPI schema
openapi_schema = get_openapi(
    title=app.title,
    version=app.version,
    description=app.description,
    routes=app.routes,
)

# 添加 SSE 响应示例（统一格式）
if "/stream/recognize/{session_id}" in openapi_schema["paths"]:
    openapi_schema["paths"]["/stream/recognize/{session_id}"]["get"]["responses"]["200"] = {
        "description": "SSE事件流（格式与 llm_chat 统一）",
        "content": {
            "text/event-stream": {
                "examples": {
                    "start": {
                        "summary": "连接开始",
                        "value": "event: start\ndata: {\"status\":\"connected\",\"timestamp\":\"2024-01-01T00:00:00\",\"session_id\":\"xxx\"}\n\n"
                    },
                    "message": {
                        "summary": "识别结果",
                        "value": "event: message\ndata: {\"type\":\"partial\",\"text\":\"你好\",\"timestamp\":\"2024-01-01T00:00:00\",\"session_id\":\"xxx\"}\n\n"
                    },
                    "ping": {
                        "summary": "心跳",
                        "value": "event: ping\ndata: {\"status\":\"ping\",\"timestamp\":\"2024-01-01T00:00:00\",\"session_id\":\"xxx\"}\n\n"
                    },
                    "end": {
                        "summary": "会话结束",
                        "value": "event: end\ndata: {\"status\":\"completed\",\"timestamp\":\"2024-01-01T00:00:00\",\"session_id\":\"xxx\"}\n\n"
                    },
                    "error": {
                        "summary": "错误",
                        "value": "event: error\ndata: {\"code\":500,\"message\":\"错误信息\",\"timestamp\":\"2024-01-01T00:00:00\",\"session_id\":\"xxx\"}\n\n"
                    }
                }
            }
        }
    }

# 保存到文件
output_path = Path(__file__).parent / "doc" / "openapi.json"
output_path.parent.mkdir(exist_ok=True)

with open(output_path, "w", encoding="utf-8") as f:
    json.dump(openapi_schema, f, indent=2, ensure_ascii=False)

print(f"✅ OpenAPI 文档已生成: {output_path}")